﻿using System;
using System.IO;

namespace FirstFloor.Documents.IO
{
    /// <summary>
    /// Provides methods for reading and writing files to temp disk storage.
    /// </summary>
    internal class TempDiskStore
    {
        private string tempFolder;

        /// <summary>
        /// Initializes a new instance of the <see cref="TempDiskStore"/> class.
        /// </summary>
        public TempDiskStore()
        {
            this.tempFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "DocumentToolkit\\Temp");

            if (!Directory.Exists(this.tempFolder)) {
                Directory.CreateDirectory(this.tempFolder);
            }
            else {
                // try to delete current temp files
                var directory = new DirectoryInfo(this.tempFolder);

                foreach (var file in directory.EnumerateFiles("*.tmp")) {
                    try {
                        file.Delete();
                    }
                    catch (Exception) {
                    }
                }
            }
        }

        /// <summary>
        /// Writes the contents of specified stream to a temp file.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public string WriteToTempFile(Stream stream)
        {
            if (stream == null) {
                throw new ArgumentNullException("stream");
            }
            var tempPath = GetNewTempFileName();
            using (var fs = File.OpenWrite(tempPath)) {
                stream.CopyTo(fs);
            }
            return tempPath;
        }

        /// <summary>
        /// Gets the full path of a new unique temp file.
        /// </summary>
        /// <returns></returns>
        public string GetNewTempFileName()
        {
            var fileName = string.Format("{0}.tmp", Guid.NewGuid());

            return Path.Combine(this.tempFolder, fileName);
        }
    }
}
